package cn.wk.service.impl;

import cn.wk.constant.CourseTypeConstant;
import cn.wk.domain.CourseType;
import cn.wk.mapper.CourseTypeMapper;
import cn.wk.service.ICourseTypeService;
import cn.wk.vo.CrumbsVo;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程目录 服务实现类
 * </p>
 *
 * @author wk
 * @since 2021-03-06
 */
//@Service
public class CourseTypeServiceImpl_cache extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService {
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Cacheable(cacheNames = CourseTypeConstant.COURSE_TYPE,key = "'All'")
    public List<CourseType> treeData() {

        return resultList();
        //这是sql循环
        //return courseTypeMapper.treeData();
    }

    @Override
    public List<CrumbsVo> getCrumbs(Long crouseTypeId) {
        return null;
    }

    @Override
    @CacheEvict(cacheNames = CourseTypeConstant.COURSE_TYPE,key = "'All'")
    public boolean insert(CourseType entity) {
        return super.insert(entity);
    }

    @Override
    @CacheEvict(cacheNames = CourseTypeConstant.COURSE_TYPE,key = "'All'")
    public boolean deleteById(Serializable id) {
        return super.deleteById(id);
    }

    private List<CourseType> resultList() {
        System.out.println("------------数据库---------------------");
        List<CourseType> list = courseTypeMapper.selectList(null);
        //准备一个新list用来返回
        List<CourseType> result = new ArrayList<>();
        //准备一个map
        HashMap<Long, CourseType> map = new HashMap<>();
        //id 对象
        list.forEach(cType -> {
            map.put(cType.getId(),cType);
        });
        list.forEach(courseType -> {
            Long pid = courseType.getPid();
            if(pid.intValue() == 0){
                result.add(courseType);
            }else{
                //这里是子节点
                //获取父级对象
                CourseType type = map.get(pid);
                type.getChildren().add(courseType);
            }
        });
        return result;
    }
}
